/** 
 * 学习目标：综合案例
 * 
 * */
import React from "react";
import CommentList from "./components/CommentList";
import Header from "./components/Header";
import "./index.css"
export default class App extends React.Component {
    state = {
        showOwner: JSON.parse(localStorage.getItem('showOwner')) || false,
        list: JSON.parse(localStorage.getItem('comList')) || [
            {
                id: 1,
                username: '思聪',
                content: '想你的夜',
            },
            {
                id: 2,
                username: '思聪2',
                content: '想你的夜2',
            },
            {
                id: 3,
                username: '思聪3',
                content: '想你的夜3',
            },
        ]
    };

    // 提交
    handleAdd = (newItem) => {
        const { list } = this.state
        console.log(newItem);
        this.setState({
            list: [{ id: Date.now(), ...newItem }, ...list]
        })
    }
    // 删除
    handleDel = (id) => {
        this.setState({ list: this.state.list.filter(item => item.id !== id) })
    }
    // 清空列表
    removeList = () => {
        this.setState({ list: [] })
    }
    showList = () => {
        const { list, showOwner } = this.state
        return list.filter(item => (!showOwner || item.username === '思聪'))
    }
    render() {
        const { showOwner } = this.state
        // console.log(this.showList());
        return (
            <div className="app">
                {/* 表单提交的时候，运行发布评论的函数 */}
                <Header handleAdd={this.handleAdd} removeList={this.removeList}></Header>
                <button onClick={() => this.setState({ showOwner: !showOwner })}>只看楼主</button>
                <CommentList showOwner={showOwner} list={this.showList()} handleDel={this.handleDel}></CommentList>
            </div >
        );
    }
    // 
    componentDidUpdate() {
        // 做前端缓存
        localStorage.setItem('comList', JSON.stringify(this.state.list))
        localStorage.setItem('showOwner', JSON.stringify(this.state.showOwner))
    }
}

